package com.suning.sawp.service.encrypt;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;

/**
 * 会员的密码加密方法
 * 
 * @author 14062651
 * 
 */
public class CryptUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CryptUtils.class);
    private static final String DEFAULT_SECURITY_KEY = "c465fbe3577fa5480b4cb1f734e65cc3";
    private static final String DES = "DES";

    public CryptUtils() {
    }

    public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
        //
        SecureRandom sr = new SecureRandom();
        //
        DESKeySpec dks = new DESKeySpec(key);
        //
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        //
        Cipher cipher = Cipher.getInstance(DES);
        //
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        //
        //
        return cipher.doFinal(src);
    }

    public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        return cipher.doFinal(src);
    }

    public final static String decrypt(String data, String key) throws Exception {
        try {
            if (key != null) {
                return new String(decrypt(hex2byte(data.getBytes(Charsets.UTF_8)), key.getBytes(Charsets.UTF_8)));
            }
            return new String(
                    decrypt(hex2byte(data.getBytes(Charsets.UTF_8)), DEFAULT_SECURITY_KEY.getBytes(Charsets.UTF_8)));
        } catch (java.security.InvalidKeyException ex) {
            LOGGER.error("InvalidKeyException ERROR", ex);
            throw ex;
        } catch (javax.crypto.BadPaddingException ex) {
            LOGGER.error("BadPaddingException ERROR", ex);
            throw ex;
        } catch (javax.crypto.IllegalBlockSizeException ex) {
            LOGGER.error("IllegalBlockSizeException ERROR", ex);
            throw ex;
        } catch (Exception e) {
            LOGGER.error("Exception ERROR", e);
            throw e;
        }
    }

    public final static String encrypt(String data, String key) {
        try {
            if (key != null) {
                return byte2hex(encrypt(data.getBytes(Charsets.UTF_8), key.getBytes(Charsets.UTF_8)));
            }
            return byte2hex(encrypt(data.getBytes(Charsets.UTF_8), DEFAULT_SECURITY_KEY.getBytes(Charsets.UTF_8)));
        } catch (Exception e) {
            LOGGER.error("加密失败,失败原因:", e);
        }
        return null;

    }

    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("=========hex2byte throw IllegalArgumentException");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }

        return b2;
    }

}
